package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchant.util.ExcelDataUtil;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.controller.util.IDNumberCheckUtil;
import cc.linker.steplink.crm.dao.CrmHelperDao;
import cc.linker.steplink.crm.dao.ScoreLogDao;
import cc.linker.steplink.crm.domain.Customer;
import cc.linker.steplink.crm.domain.CustomerInfo;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.service.CustomerIntegralService;
import cc.linker.steplink.crm.merchanth5.service.VipCustomerLogService;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.merchanth5.util.MD5;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.response.ResponseException;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.IPersonalCenterService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 客户管理&分群管理
 *
 * @author wuyue 2019-05-30
 */
@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerController {

    private CustomerService customerService;
    private ScoreLogDao scoreLogDao;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private CrmHelperDao crmHelperDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CustomerIntegralService customerIntegralService;
    @Autowired
    private IPersonalCenterService personalCenterService;
    @Autowired
    private VipCustomerLogService vipCustomerLogService;
    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private CommonsService commonsService;

    @Autowired
    public CustomerController(CustomerService customerService, ScoreLogDao scoreLogDao) {
        this.customerService = customerService;
        this.scoreLogDao = scoreLogDao;
    }

    @GetMapping("/customerclassify")
    public Map<String, Object> customerClassify(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return customerService.customerClassify(userinfo.getOrgId());
    }

    /**
     * 客户列表
     *
     * @param map      json格式的参数映射到map,下同
     * @param end      截止时间
     * @param keyword  关键字
     * @param level    等级
     * @param my       是否展示我的客户(有值就只展示我的客户)
     * @param pageSize 每页显示多少条(默认20)
     * @param pn       当前页码(默认1)
     * @param source   来源(0:手动录入1:idp2:微信)
     * @param start    开始时间
     * @param status   分配状态(0:未分配1:已分配)
     * @param session  用于获取当前用户信息,下同
     * @return PageInfo<>(list)
     */
    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        int pn = 1, pageSize = 10;
        Object pno = map.get("pn");
        if (pno instanceof Integer && !StringUtils.isEmpty(pno)) {
            pn = (int) pno;
        }
        Object pageSizeo = map.get("pageSize");
        if (pageSizeo instanceof Integer && !StringUtils.isEmpty(pageSizeo)) {
            pageSize = (int) pageSizeo;
        }
        PageHelper.startPage(pn, pageSize);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        // 是否只展示我的客户
        if (!StringUtils.isEmpty(map.get("my"))) {
            String adminId = userinfo.getAdminId();
            map.put("adminId", adminId);
        }
        // 根据标签筛选
        String labelIds = (String) map.get("labelIds");
        if (!StringUtils.isEmpty(labelIds)) {
            String[] split = labelIds.split(",");
            List<String> list = Arrays.asList(split);
            map.put("labelId", list);
        }
        String source = (String) map.get("source");
        List<String> sourceIds = new ArrayList<>();
        if (!StringUtils.isEmpty(source)) {
            if ("1".equals(source) || "2".equals(source) || "3".equals(source)) {
                sourceIds.add("2");
            } else if ("5".equals(source)) {
                sourceIds.add("58");
            } else {
                sourceIds = Arrays.asList(source.split(","));
            }
            map.put("sources", sourceIds);
        }
        List<String> barSourceIds = new ArrayList<>();
        if (!StringUtils.isEmpty(map.get("barsource"))) {
            if (map.get("barsource").toString().equals("5")) {
                barSourceIds.add("5");
                barSourceIds.add("8");
            } else {
                barSourceIds.add(map.get("barsource").toString());
            }
            map.put("barSourceIds", barSourceIds);
        }
        return new PageInfo<>(customerService.getCustomerPageList(map));
    }


    /**
     * 导出字段包括
     * <用户ID><用户名称>＜性别＞<手机号><地区><会员等级><渠道><负责人>
     * <加入时间><公司名称><身份证><出生日期><微信><传真><邮箱><省市区><详细地址><标签>；
     * @param map
     * @param request
     * @return
     */
    @GetMapping("/exportlist")
    public void exportList(HttpServletRequest request,
                           HttpServletResponse response,
                           @RequestParam(value = "barsource", defaultValue = "", required = false) String barsource,
                           @RequestParam(value = "end", defaultValue = "", required = false) String end,
                           @RequestParam(value = "gender", defaultValue = "", required = false) Integer gender,
                           @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword,
                           @RequestParam(value = "levelId", defaultValue = "", required = false) String levelId,
                           @RequestParam(value = "my", defaultValue = "", required = false) String my,
                           @RequestParam(value = "source", defaultValue = "", required = false) String source,
                           @RequestParam(value = "start", defaultValue = "", required = false) String start,
                           @RequestParam(value = "status", defaultValue = "", required = false) String status,
                           @RequestParam(value = "labelIds", defaultValue = "", required = false) String labelIds
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);

        if (!StringUtils.isEmpty(end)) {
            map.put("end", end);
        }
        if (!StringUtils.isEmpty(gender)) {
            map.put("gender", gender);
        }
        if (!StringUtils.isEmpty(keyword)) {
            map.put("keyword", keyword);
        }
        if (!StringUtils.isEmpty(levelId)) {
            map.put("levelId", levelId);
        }
        if (!StringUtils.isEmpty(start)) {
            map.put("start", start);
        }
        if (!StringUtils.isEmpty(status)) {
            map.put("status", status);
        }
        // 是否只展示我的客户
        if (!StringUtils.isEmpty(my)) {
            String adminId = userinfo.getAdminId();
            map.put("adminId", adminId);
        }
        // 根据标签筛选
        if (!StringUtils.isEmpty(labelIds)) {
            String[] split = labelIds.split(",");
            List<String> list = Arrays.asList(split);
            map.put("labelId", list);
        }
        if (!StringUtils.isEmpty(source)) {
            if ("1".equals(source) || "2".equals(source) || "3".equals(source)) {
                source = "2";
            }
            if ("5".equals(source)) {
                source = "58";
            }
            map.put("source", source);
        }

        if (!StringUtils.isEmpty(barsource)) {
            if ("5".equals(barsource)) {
                barsource = "5,8";
            }
            map.put("barsource", barsource);
        }
        List<Map<String, Object>> customerList = customerService.listCustomer(map);
        String[] key = {"customerId", "nickName", "customerPhone",IntegralEnums.customerScore.toString(),IntegralEnums.customerGrowthScore.toString(), "customerCompany", "customerIdcard", "customerBirth", "customerWxcode", "customerFax", "customerEmail", "customerAreaStr", "customerAddress", "labelName"};
        String[] title = {"用户编号", "用户名称", "手机号","积分","成长值", "公司名称", "身份证", "出生日期", "微信", "传真", "邮箱", "省市区", "详细地址", "标签"};
        customerList = this.customerService.assembleCustomerExportInfo(customerList,userinfo.getOrgId());
        commonsService.excelDownload(customerList, key, title, "用户列表", response);
    }

    /**
     * 获取导入模板
     * @param response
     * @throws Exception
     */
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws Exception {
        String[] key = {"a","b","c","d","e","f","g","h","i","j","k","l"};
        List<Map<String, Object>> customerList = new ArrayList<>();
        Map<String,Object> data = new HashMap<>();
        data.put("a","C20200910557R81(示例)");
        data.put("b","小明(示例)");
        data.put("c","13000000000(示例)");
        data.put("d","北京远大集团(示例)");
        data.put("e","342900199011112000(示例)");
        data.put("f","1990-11-11(示例)");
        data.put("g","13000000000(示例)");
        data.put("h","666666666666(示例)");
        data.put("i","youxiang@163.com(示例)");
        data.put("j","浙江省杭州市滨江区(示例)");
        data.put("k","秋意路535号(示例)");
        data.put("l","宅男,运动,旅游(示例)");
        customerList.add(data);
        String[] title = {"用户编号(必填)","用户名称(选填)","手机号(必填)","公司名称(选填)","身份证号码(选填)","出生日期(选填)","微信(选填)","传真(选填)","邮箱(选填)","省市区(选填)","详细地址(选填)","标签(选填)"};
        commonsService.excelDownload(customerList,key,title,"用户信息批量导入表格模板",response);
    }


    /**
     * 导入用户数据
     * @param file
     * @param type
     * @param request
     * @return
     */
    @PostMapping(value = "/importExcelData")
    @ResponseBody
    public Map<String, Object> importExcelData(MultipartFile file, Integer type, HttpServletRequest request) throws ParseException {
        List<Map<String, String>> list ;
        try {
            list = ExcelDataUtil.getAllByExcel(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw GlobalException.build("导入表格格式错误，与导入模板不符");
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        List<Map<String, Object>> resList = new ArrayList<>();
        String tempUuid = UUID.randomUUID().toString();
        String key = "customer:customerexceldata_"+orgId+"_"+tempUuid+"_"+type;
        for (int i = 1; i < list.size(); i++) {
            Map<String, String> dataMap = list.get(i);
            Map<String, Object> data = new HashMap<>();
            data.put("customerId",dataMap.get("0")==null?"":dataMap.get("0"));//用户ID
            data.put("nickName",dataMap.get("1")==null?"":dataMap.get("1"));//1用户名称
            data.put("infoCustomerPhone",dataMap.get("2")==null?"":dataMap.get("2"));//1手机号
            data.put("customerCompany",dataMap.get("3")==null?"":dataMap.get("3"));//1公司名称
            data.put("customerIdcard",dataMap.get("4")==null?"":dataMap.get("4"));//1身份证
            String customerBirth;
            if(StringUtils.isEmpty(dataMap.get("5"))){
                customerBirth = null;
            }else{
                customerBirth = dataMap.get("5");
            }
            data.put("customerBirth",customerBirth);//1出生日期
            data.put("customerWxcode",dataMap.get("6")==null?"":dataMap.get("6"));//1微信
            data.put("customerFax",dataMap.get("7")==null?"":dataMap.get("7"));//1传真
            data.put("customerEmail",dataMap.get("8")==null?"":dataMap.get("8"));//1邮箱
            data.put("customerAreaStr",dataMap.get("9")==null?"":dataMap.get("9"));//省市区
            data.put("customerAddress",(dataMap.get("9")==null?"":dataMap.get("9"))+(dataMap.get("10")==null?"":dataMap.get("10")));//1详细地址
            data.put("labelName",dataMap.get("11")==null?"":dataMap.get("11"));//标签
            data.put("customerAddressDetail",dataMap.get("10")==null?"":dataMap.get("10"));//详细地址
            //判断是否是空记录
            boolean flag = true;
            for (Map.Entry<String, Object> next : data.entrySet()) {
                if (!StringUtils.isEmpty(next.getValue())) {
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                resList.add(data);
                stringRedisTemplate.opsForSet().add(key,JSON.toJSONString(data));
            }
        }
        stringRedisTemplate.expire(key, 1, TimeUnit.DAYS);
        Map<String,Object> data = new HashMap<>();
        data.put("tempuuid",tempUuid);
        data.put("list",resList);
        return data;
    }

    /**
     * 批量修改数据
     * @param map
     * @param request
     */
    @PostMapping("/savecustomerexceldata")
    public void saveCustomerExcelData(@RequestBody Map<String, String> map, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String remark = map.get("remark");
        String uuid = map.get("tempuuid");
        String key = "customer:customerexceldata_"+orgId+"_"+uuid+"_*";
        Set<String> keys = stringRedisTemplate.keys(key);

        if(null!=keys && keys.size()>0){
            for(String sk:keys){
                String[] sp = sk.split("_");
                String type = sp[3];
                Set<String> membersList = stringRedisTemplate.opsForSet().members(sk);
                if(null!=membersList && membersList.size()>0){
                    int success = 0;
                    int fail = 0;
                    int all = 0;
                    Map<String,Object> batch = new HashMap<>();
                    batch.put("allNum",all);
                    batch.put("successNum",success);
                    batch.put("failNum",fail);
                    batch.put("remark",remark);
                    batch.put("orgId",orgId);
                    batch.put("createUser",userinfo.getAdminId());
                    batch.put("status",2);
                    customerService.addBatch(batch);
                    String tempUuid = UUID.randomUUID().toString();
                    for(String mem:membersList){
                        Map<String,Object> customerData = (Map<String,Object>)JSON.parse(mem);
                        customerData.put("saveType",Integer.parseInt(type));
                        customerData.put("orgId",orgId);
                        customerData.put("tempUuid",tempUuid);
                        String customerId = customerData.get("customerId").toString();
                        int res = customerService.saveCustomer(customerData);
                        all++;
                        int status = 0;
                        String labelNameStr = "";
                        if(res == 1){
                            status = 1;
                            success++;
                            String t = stringRedisTemplate.opsForValue().get("customer:customer_label_" + tempUuid + customerId);
                            labelNameStr = t==null?"":t;
                        }else{
                            fail++;
                            if(!StringUtils.isEmpty(customerData.get("labelName"))){
                                labelNameStr = customerData.get("labelName").toString();
                            }
                        }
                        customerData.put("status",status);
                        customerData.put("batchId",-1);
                        customerData.put("labelName",labelNameStr);
                        customerService.addBatchLog(customerData);
                    }
                    batch.put("batchId",batch.get("batchId"));
                    batch.put("status",1);
                    batch.put("allNum",all);
                    batch.put("successNum",success);
                    batch.put("failNum",fail);
                    customerService.saveBatch(batch);
                    batch.put("tempUuid",tempUuid);
                    customerService.saveBatchLog(batch);
                }
            }
        }

    }

    /**
     * 获取导入记录
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getBatchList")
    public PageInfo getBatchList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> map = new HashMap<>();
        map.put("orgId",orgId);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(customerService.getBatchList(map));
    }


    /**
     * 获取导入详情
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getBatchLogList")
    public Map<String,Object> getBatchLogList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
            Integer batchId,
            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> map = new HashMap<>();
        map.put("orgId",orgId);
        map.put("batchId",batchId);
        if(!StringUtils.isEmpty(status)){
            map.put("status",status);
        }
        Map<String,Object> batchInfo = customerService.getBatchInfo(batchId);
        Map<String,Object> res = new HashMap<>();
        res.put("batchInfo",batchInfo);
        PageHelper.startPage(pageIndex, pageSize);
        res.put("list",new PageInfo<>(customerService.getBatchLogList(map)));
        return res;
    }

    /**
     * 客户详情
     *
     * @param id
     * @return Map<String, Object>
     * @throws GlobalException
     */
    @GetMapping("/get")
    public Object get(String id,HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return customerService.getCustomer(id,userinfo.getOrgId());
    }

    /**
     * 客户概要(跟踪记录)
     *
     * @param id    客户id
     * @param start 开始时间
     * @param end   截止时间
     * @param type  类型
     * @return List<Map < String, String>>
     * @throws GlobalException
     */
    @PostMapping("/outline")
    public Object outline(@RequestBody Map<String, Object> map) throws GlobalException {
        return customerService.getOutLine(map);
    }

    /**
     * 用户动态
     *
     * @param customerId 用户id
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param pageIndex  页码
     * @param pageSize   页大小
     */
    @PostMapping("/dynamic")
    public Object dynamic(@RequestBody Map<String, Object> map) {
        return customerService.dynamic(map);
    }

    /**
     * 客户资料(stepLink、idp、微信)
     *
     * @param id
     * @return Map<String, Object>
     * key = customer, value = Map<String, String>
     * key = idp, value = List<KeyNameValue>
     * key = wx, value = null(暂无微信用户)
     * @throws GlobalException
     */
    @GetMapping("/data")
    public Object data(String id) throws GlobalException {
        return customerService.getData(id);
    }

    /**
     * 客户标签
     *
     * @param id
     * @param session
     * @return List<Map < String, String>>
     * @throws GlobalException
     */
    @GetMapping("/label")
    public Object label(String id, Integer pn, Integer pageSize, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        map.put("pn", pn);
        map.put("pageSize", pageSize);
        return customerService.getLabel(map);
    }

    /**
     * 新增客户
     *
     * @param map
     * @param customerAddress 详细地址
     * @param customerArea    区域
     * @param customerCompany 公司
     * @param customerEmail   邮箱
     * @param customerFax     传真
     * @param customerName    客户姓名(必须)
     * @param customerPhone   手机号
     * @param customerWxcode  微信
     * @param session
     * @throws Exception
     */
    @PostMapping("/insert")
    public void insert(@RequestBody Map<String, Object> map, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Object idNum = map.get("idNum");
        if (null != idNum && !"".equals(idNum)) {
            boolean flag = IDNumberCheckUtil.isIDNum((String) idNum);
            if (!flag) {
                throw GlobalException.build("请输入正确的身份证号码");
            }
        }
        String adminId = userinfo.getAdminId();
        map.put("createUser", adminId);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        Customer customer = BeanMapUtils.mapToBean(map, Customer.class);
        CustomerInfo customerInfo = BeanMapUtils.mapToBean(map, CustomerInfo.class);
        customerService.insertCustomer(customer, customerInfo);
    }

    /**
     * 编辑客户
     *
     * @param map
     * @param customerAddress 详细地址
     * @param customerArea    区域
     * @param customerCompany 公司
     * @param customerEmail   邮箱
     * @param customerFax     传真
     * @param customerId      客户id(必须)
     * @param customerName    客户姓名
     * @param customerPhone   手机号
     * @param customerWxcode  微信
     * @param session
     * @throws Exception
     */
    @PostMapping("/edit")
    public void edit(@RequestBody Map<String, Object> map, HttpServletRequest request) throws Exception {
        if(StringUtils.isEmpty(map.get("birthday"))){
            map.put("birthday",null);
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Object idNum = map.get("IDNum");
        if (null != idNum && !"".equals(idNum)) {
            boolean flag = IDNumberCheckUtil.isIDNum((String) idNum);
            if (!flag) {
                throw GlobalException.build("请输入正确的身份证号码");
            }
        }
        Customer customer = BeanMapUtils.mapToBean(map, Customer.class);
        CustomerInfo customerInfo = BeanMapUtils.mapToBean(map, CustomerInfo.class);
        customerService.updateCustomer(customer, customerInfo, userinfo);
    }

    /**
     * 新增备注
     *
     * @param map
     * @param customerId  客户id
     * @param trackRemark 备注内容
     * @param session
     * @throws Exception
     */
    @PostMapping("/note")
    public void note(@RequestBody Map<String, String> map, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        customerService.note(adminId, map.get("customerId"), map.get("trackRemark"));
    }

    /**
     * 变更负责人
     *
     * @param map
     * @param adminId    新负责人id
     * @param customerId 客户id
     * @param session
     * @throws GlobalException
     */
    @PostMapping("/change")
    public void change(@RequestBody Map<String, String> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String operateId = userinfo.getAdminId();
        // 获取当前用户id为operateId
        map.put("operateId", operateId);
        customerService.change(map);
    }

    /**
     * 分群列表
     *
     * @param pn
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/group/list")
    public Object groupList(@RequestParam(value = "pn", defaultValue = "1", required = false) Integer pn,
                            @RequestParam(value = "pageSize", defaultValue = "20", required = false) Integer pageSize,
                            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pn, pageSize);
        String orgId = userinfo.getOrgId();
        return new PageInfo<>(customerService.listGroup(orgId));
    }

    /**
     * 手动刷新人群数量
     * @param session
     */
    @GetMapping("/group/refresh")
    public void refreshGroup(@RequestParam(value = "groupIds", defaultValue = "", required = false) String groupIds,HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("groupIds", groupIds);
        customerService.refreshGroup(map);
    }

    /**
     * 分群详情
     *
     * @param id
     * @return
     * @throws GlobalException
     */
    @GetMapping("/group/get")
    public Object groupGet(String id) throws GlobalException {
        return customerService.getGroup(id);
    }

    /**
     * 新增分群
     *
     * @param map
     * @param groupName 分群名称
     * @param include   分群规则
     * @param session
     */
    @PostMapping("/group/insert")
    public void groupInsert(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        map.put("adminId", adminId);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        customerService.insertGroup(map);
        dynamicService.recording(adminId, orgId, 7,"新增"+map.get("groupName"));
    }

    /**
     * 分群编辑
     *
     * @param map
     * @param groupId   分群ID(必须)
     * @param groupName 分群名称
     * @param include   分群规则
     * @param session
     * @throws GlobalException
     */
    @PostMapping("/group/edit")
    public void groupEdit(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        map.put("adminId", adminId);
        String orgId = userinfo.getOrgId();
        map.put("orgId", orgId);
        customerService.editGroup(map);
    }

    /**
     * 分群删除
     *
     * @param id
     */
    @GetMapping("/group/del")
    public void groupDel(String id, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String[] split = id.split(",");
        List<String> groupIds = Arrays.asList(split);
        for(String gid:groupIds) {
            Map<String, Object> group = customerService.getGroup(gid);
            dynamicService.recording(request, 8,"删除"+group.get("groupName"));
        }
        customerService.delGroup(groupIds, orgId);
    }

    /**
     * 获取所有分群名和ID
     *
     * @return List<Map < String, String>>
     */
    @GetMapping("/group/name")
    public Object groupName(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        return customerService.getGroupName(orgId);
    }

    /**
     * 群名判重
     *
     * @param name 分群名
     * @return
     */
    @GetMapping("/group/repeat")
    public boolean repeat(String name, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, String> map = new HashMap<>();
        map.put("groupName", name);
        map.put("orgId", orgId);
        int i = customerService.judgeGroupNameRepeat(map);
        return i > 0;
    }


    @PostMapping("/getscoreinfo")
    public Object getscore(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if (null == map.get("customerId") || "".equals(map.get("customerId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Map<String, Object> info = new HashMap<>();
        int customerScore = customerService.getCustomerScore(map.get("customerId").toString());
//        String levelName = CallService.getCustomerLevel(map.get("customerId").toString());
        String levelName = customerService.getCustomerLevel(map.get("customerId").toString());

        if (null == levelName || "".equals(levelName)) {
            levelName = "普通用户";
        }
        info.put("customerScore", customerScore);
        info.put("levelName", levelName);
        return info;
    }

    @PostMapping("/setscore")
    public void setscore(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if (null == map.get("customerId") || "".equals(map.get("customerId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        String customerId = map.get("customerId").toString();
        if (null == map.get("score") || "".equals(map.get("score"))) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Integer score = Integer.parseInt(map.get("score").toString());
//        int customerScore = customerService.getCustomerScore(map.get("customerId").toString());
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        Long customerScore = 0L;
        if (integralCustomerInfo != null && !StringUtils.isEmpty(integralCustomerInfo.get("customerScore"))) {
            customerScore = Long.valueOf(integralCustomerInfo.get("customerScore").toString());
        }
        if (Integer.parseInt(map.get("score").toString()) > 999999999) {
            throw new GlobalException(new ResponseException(400, "超过最大值"));
        }
        if ((Integer.parseInt(map.get("score").toString()) + customerScore) < 0) {
            throw new GlobalException(new ResponseException(400, "超过用户积分最大值"));
        }
        Map<String, Object> log = new HashMap<String, Object>();
        log.put("logId", UUID.randomUUID().toString());
        log.put("customerId", map.get("customerId").toString());
        log.put("scoreValue", map.get("score"));
        log.put("scoreType", 0);
        log.put("actionRemark", userinfo.getAdminName());
        scoreLogDao.add(log);
        String msg = "系统";
        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (score >= 0) {
            msg = msg + "赠送";
        } else {
            msg = msg + "扣除";
        }
        this.customerIntegralService.addIntegralCustomerLog(customerId, msg, IntegralEnums.customerScore.toString(), score.toString(), IntegralEnums.other.toString(), orgId);
        stringRedisTemplate.delete("home:customer_info_" + map.get("customerId").toString());
    }

    @PostMapping("/setGrowth")
    public void setGrowth(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
            String orgId = userinfo.getOrgId();
            if (StringUtils.isEmpty(orgId)) {
                throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
            }
        if (null == map.get("customerId") || "".equals(map.get("customerId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        String customerId = map.get("customerId").toString();
        if (null == map.get("growth") || "".equals(map.get("growth"))) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Integer growth = Integer.parseInt(map.get("growth").toString());
//        int customerScore = customerService.getCustomerScore(map.get("customerId").toString());
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        Long customerGrowthScore = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            customerGrowthScore = Long.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
        }
        if (Integer.parseInt(map.get("growth").toString()) > 999999999) {
            throw new GlobalException(new ResponseException(400, "超过最大值"));
        }
        if ((Integer.parseInt(map.get("growth").toString()) + customerGrowthScore) < 0) {
            throw new GlobalException(new ResponseException(400, "超过用户积分最大值"));
        }
//        customerService.setCustomerScore(map);

        Map<String, Object> log = new HashMap<String, Object>();
        log.put("logId", UUID.randomUUID().toString());
        log.put("customerId", map.get("customerId").toString());
        log.put("growthValue", map.get("growth"));
        log.put("growthType", 0);
        log.put("actionRemark",userinfo.getAdminName());
        scoreLogDao.addGrowth(log);
        String msg = "系统";
        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(growth>=0){
            msg = msg+"赠送";
        }else {
            msg = msg+"扣除";
        }
        this.customerIntegralService.addIntegralCustomerLog(customerId,msg, IntegralEnums.customerGrowthScore.toString(),growth.toString(),IntegralEnums.other.toString(),orgId);
        if(growth>=0) {
            vipCustomerLogService.growthOpenAccount(customerId, orgId,customerGrowthScore,null);
        }
        Integer isVip = vipCustomerLogService.getIsVip(customerId,orgId);
        String globalopenId = vipCustomerLogDao.getGlobalopenIdByCustomerId(customerId);
        if(StringUtils.isEmpty(globalopenId)){
            globalopenId = vipCustomerLogDao.getAppUserIdByCustomerId(customerId);
        }
        String key = MD5.encode(orgId + globalopenId);
        String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
        if(!StringUtils.isEmpty(h5User)){
            WxUser wxUser = JSON.parseObject(h5User, WxUser.class);
            wxUser.setIsVip(isVip);
            h5User = JSON.toJSONString(wxUser);
            stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
        }
        stringRedisTemplate.delete("home:customer_info_" + map.get("customerId").toString());
    }

    /**
     * @param customerId
     * @param start
     * @param end
     * @return
     * @throws GlobalException
     */
    @PostMapping("/getactionlog")
    public List getactionlog(@RequestBody Map<String, String> map) throws GlobalException {
        if (null == map || StringUtils.isEmpty(map.get("customerId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        return customerService.getActionLog(map);
    }

    /**
     * @param customerId
     * @param start
     * @param end
     * @return
     * @throws GlobalException
     */
    @PostMapping("/getactioncontent")
    public Object getactioncontent(@RequestBody Map<String, String> map) throws GlobalException {
        if (null == map || StringUtils.isEmpty(map.get("customerId"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        List<Map<String, Object>> actionContent = customerService.getActionContent(map);
        for (Map<String, Object> res : actionContent) {
            if (null != res) {
                if ("7".equals(res.get("actionType").toString())) {
                    if (null != res.get("actionRemark") && null != res.get("readTime")) {
                        res.put("actionRemark", res.get("actionRemark").toString());
                    }
                }
                res.remove("actionType");
            }
        }
        if (actionContent.size() > 0) {
            return actionContent;
        }
        return new ArrayList<>();
    }

    /**
     * @param customerId 客户id
     * @param start      开始时间
     * @param end        截止时间
     * @return
     */
    @PostMapping("/listscore")
    public Object listScore(@RequestBody Map<String, String> map) {
        return scoreLogDao.listScore(map);
    }

    /**
     * @param customerId 客户id
     * @param start      开始时间
     * @param end        截止时间
     * @return
     */
    @PostMapping("/listGrowth")
    public Object listGrowth(@RequestBody Map<String, String> map) {
        return scoreLogDao.listGrowth(map);
    }

    @GetMapping("/getlistcustomerbycid")
    public Map<String, Object> getListCustomerByCid(String id, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        return customerService.getListCustomerByCid(id, orgId);
    }

    /**
     * @Description: 支付宝用户订单列表
     * @Param: customerId : 客户id
     * @Param: lastId : 上一次最后一条id
     * @Param: pageSize : 页面大小
     **/
    @PostMapping("/alipayOrders")
    @ResponseBody
    public Object alipayOrders(@RequestBody Map<String, Object> params) {
        Map<String, String> header = new HashMap<String, String>() {{
            put("Content-Type", "application/json;charset=UTF-8");
        }};
        Map map = new HashMap();
        map = crmHelperDao.getAlipayParam(params);
        String url = systemProperties.getQtPayUrl() + "get/user/orders";
        // 请求oss结果
        String result = "";
        try {
            if (params.get("lastId") != null && !"".equals(params.get("lastId").toString())) {
                map.put("lastId", Integer.valueOf(params.get("lastId").toString()));
            }
            if (params.get("pageSize") != null && !"".equals(params.get("pageSize").toString())) {
                map.put("pageSize", Integer.valueOf(params.get("pageSize").toString()));
            }
            result = httpService.doPost(url, JSON.toJSONString(map), header);
            if (result == null || "".equals(result)) {
                result = "{\"rt\":0,\"des\":\"蜻蜓支付调用异常\"}";
            }
        } catch (Exception e) {
            //LOGGER.error("蜻蜓支付调用异常", e);
            result = "{\"rt\": 1,\"des\": \"成功\",\"data\": {\"data\": [],\"lastId\": null,\"currentSize\":10000} }";
        }
        return result;
    }


    /**
     * 分群列表（对外）
     *
     * @param : orgId 机构id
     * @return
     */
    @PostMapping("/group/openList")
    public Object openList(@RequestBody Map<String, Object> params) {
        String orgCode = "";
        if(StringUtils.isEmpty(params.get("orgCode"))){
            throw GlobalException.build("参数错误！");
        }else {
            orgCode = params.get("orgCode").toString();
        }
        return customerService.openList(orgCode);
    }

    /**
     * 分群用户（对外）
     *
     * @param : groupIds 分群id逗号隔开
     * @return
     */
    @PostMapping("/group/userOpenIdList")
    public Object userOpenIdList(@RequestBody Map<String, Object> params) {
        String groupIds = "";
        if(StringUtils.isEmpty(params.get("groupIds"))){
            throw GlobalException.build("参数错误！");
        }else {
            groupIds = params.get("groupIds").toString();
        }
        return customerService.userOpenIdList(groupIds);
    }

    /**
    * @Description：老数据
    * @DateTime：2020/9/28 8:45
    * @Params：
    * @Return：
    */
    @GetMapping("/runOldData")
    public void runOldData(@RequestParam String customerIds, HttpServletRequest request){
        customerService.runOldData(customerIds);
    }

    /**
     * 赠送卡券
     * @param params
     * @param request
     */
    @PostMapping("/giveCoupon")
    public void giveCoupon(@RequestBody Map<String, Object> params,HttpServletRequest request){
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userInfo.getOrgId();
        params.put("orgId", orgId);
        params.put("adminId",userInfo.getSaler()?userInfo.getCustomerId():userInfo.getAdminId());
        customerService.giveCoupon(params);
    }

    /**
     * 赠送卡券
     * @param params
     * @param request
     */
    @PostMapping("/giveVip")
    public void giveVip(@RequestBody Map<String, Object> params,HttpServletRequest request){
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userInfo.getOrgId();
        params.put("orgId", orgId);
        params.put("adminId",userInfo.getSaler()?userInfo.getCustomerId():userInfo.getAdminId());
        params.put("orderSource",1);
        Long vipId = Long.valueOf(params.get("vipId").toString());
        String customerId = params.get("customerId").toString();
        Map open = vipCustomerLogService.open(params, customerId, vipId, orgId, null, "-1", null);
        params.put("vipEffectiveDays", open.get("effectiveDays")==null?0:open.get("effectiveDays"));
        params.put("vipEffectiveMonth", open.get("effectiveMonth")==null?0:open.get("effectiveMonth"));
        params.put("name", open.get("name"));
        params.put("effectiveType", open.get("effectiveType"));
        params.put("couponId", vipId);
        customerService.saveGiveLog(params);
    }

}
